package com.xdf.ecommerce.service.communication;

import com.alibaba.fastjson.JSON;
import com.xdf.ecommerce.constant.CommonConstant;
import com.xdf.ecommerce.vo.JwtToken;
import com.xdf.ecommerce.vo.UsernameAndPassword;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 使用 ribbon 不像直接使用 restTemplate，需要手动填充 host,port
 * 使用 ribbon 通信只需要填充 serviceId 即可
 * @author chanchaw
 * @create 2025-10-29 10:59
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UseRibbonService {
    private static final String URL = "http://[serviceId]/ecommerce-authority-center/authority/token";
    private final RestTemplate restTemplate;

    public JwtToken getToken(UsernameAndPassword usernameAndPassword){
        String url = URL.replace("[serviceId]", CommonConstant.AUTHORITY_CENTER_SERVICE_ID);
        log.info("实际请求的URL：[{}]", url);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return restTemplate.postForObject(
                url, new HttpEntity<>(JSON.toJSON(usernameAndPassword),httpHeaders),
                JwtToken.class
        );
    }
}
